'''
Author: bin.liu 2841208085@qq.com
Date: 2025-09-24 00:07:09
LastEditors: bin.liu 2841208085@qq.com
LastEditTime: 2025-09-24 00:15:14
FilePath: \scripts\test.py
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
'''
from deep_translator import GoogleTranslator
import requests
from requests.exceptions import ConnectTimeout, ConnectionError, ReadTimeout
import time
def translate_safely(text, target_lang='zh-CN', timeout=10):
    """安全翻译函数：添加超时和错误处理"""
    try:
        # 设置超时（秒），避免无限等待
        translator = GoogleTranslator(
            source='auto', 
            target=target_lang,
            # 自定义请求参数（添加超时）
            proxies=None,  # 如需代理可添加：{'http': 'http://代理地址', 'https': 'https://代理地址'}
            timeout=timeout
        )
        return translator.translate(text)
    except (ConnectTimeout, ReadTimeout):
        return f"错误：翻译请求超时（超过{timeout}秒），请检查网络"
    except ConnectionError:
        return "错误：无法连接到翻译服务器，请检查网络或使用国内可用服务"
    except Exception as e:
        return f"翻译失败：{str(e)}"

# 测试翻译
if __name__ == "__main__":
    print("正在翻译...")
    result = translate_safely("Hello, how are you?")
    print(f"译文：{result}")
    time.sleep(2)
    # 测试小语种翻译
    result2 = translate_safely("Bonjour le monde", target_lang='en')  # 法语→英语
    print(f"法语→英语：{result2}")
    